import { defineComponent, ref, unref } from 'vue';
import { useVModels } from '@vueuse/core';
import { useCurrentDeckStore } from '/@/store/modules/currentDeck';
import { cloneDeep, includes } from 'lodash-es';
import { Button, Popup } from 'vant';

import('./DeckTagPopup.less');

export default defineComponent({
  name: 'DeckTagPopup',
  props: {
    show: {
      type: Boolean as PropType<boolean>,
      required: true,
      default: () => {
        return false;
      },
    },
    tags: {
      type: Array as PropType<string[]>,
      required: true,
    },
  },
  emits: ['update:show', 'modifyDeckTags'],
  setup(props, { emit }) {
    const { show } = useVModels(props, emit);
    const { getDeckConfig } = useCurrentDeckStore();

    const deckTags = ref(cloneDeep(props.tags));

    const multipleClick = (text: string) => {
      if (unref(deckTags).includes(text)) {
        const index = unref(deckTags).indexOf(text);
        unref(deckTags).splice(index, 1);
      } else {
        unref(deckTags).push(text);
      }
    };

    return () => (
      <Popup
        closeable={false}
        teleport={'body'}
        round
        v-model={[show.value, 'show']}
        class={'modify-tags-popup'}
        onOpen={() => {
          deckTags.value = cloneDeep(props.tags);
        }}
      >
        <h1 class={'text-sm mb-md'}>选择标签</h1>
        <div class={'tags-area'}>
          <ul class={'box-list flex flex-wrap items-start'}>
            {getDeckConfig.tags.map((text) => {
              const isActive = includes(unref(deckTags) || [], text);
              return (
                <li
                  class={['box-item text-sm', { active: isActive }]}
                  onClick={() => {
                    multipleClick(text);
                  }}
                >
                  <span>{text}</span>
                </li>
              );
            })}
          </ul>
        </div>
        <div class={'button-box flex mt-lg'}>
          <Button
            plain
            block
            type='primary'
            class={'!w-228px !mr-lg'}
            onClick={() => {
              show.value = false;
            }}
          >
            取消
          </Button>
          <Button
            type='primary'
            block
            class={'flex-1'}
            onClick={() => {
              emit('modifyDeckTags', deckTags.value);
              show.value = false;
            }}
          >
            确认
          </Button>
        </div>
      </Popup>
    );
  },
});
